package zhixin

import (
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var (
	SERVER_HOST = "https://api.mozisms.com"
)

type Config struct {
	ApiKey string
	CustomId string
	Version string
}
type ZhiXin struct {
	conf *Config
}
type Msg struct {
	MerchantOrderId int64 `json:"merchantOrderId"`
	Sign string `json:"sign"`
	Content string `json:"content"`
	Mobiles string `json:"mobiles"`
}
type Result struct {
	Status string `json:"status"`
	Code string `json:"code"`
	Msg string `json:"msg"`
}

func NewMsg(orderId int64, sign,content,mobiles string) Msg {
	return Msg{
		MerchantOrderId: orderId,
		Sign: sign,
		Content: content,
		Mobiles: mobiles,
	}
}

func NewZhiXin(conf Config) *ZhiXin{

	return &ZhiXin{conf: &conf}
}
func (z *ZhiXin) Send(msg Msg) (msgId string, err error) {
	data,err := json.Marshal(msg)
	if err != nil {
		return
	}
	sha1Str := fmt.Sprintf("%s%s",string(data),z.conf.ApiKey)
	t := sha1.New();
	io.WriteString(t,sha1Str);
	sha1Result := fmt.Sprintf("%x",t.Sum(nil))

	client := http.Client{
		Timeout: time.Second * 3,
	}
	headers := map[string]string{
		"Content-Type": "application/json; charset=utf-8",
		"merchantId":z.conf.CustomId,
		"merchantVersion":z.conf.Version,
		"sign":sha1Result,
		"Accept":"application/json",
	}
	req,err := http.NewRequest("POST",SERVER_HOST,strings.NewReader(string(data)))
	if err != nil {
		return
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	fmt.Println("body-------------",string(body))
	var result Result
	err = json.Unmarshal(body,&result)
	if err != nil {
		return
	}
	msgId = "XXX"
	if result.Status == "1" || result.Code == "B000000" {
		return
	}
	err = fmt.Errorf("%s|%s",result.Code,result.Msg)
	return
}